var wsObj = null;
var wsUrl = null;
var userId = -1
var lockReconnect = false;//避免多次连接
var wsCreateHandler;

function createWebSocket () {
  try {
    wsObj = new WebSocket("ws://localhost:2333");
    initWsEventHandle();
  } catch (e) {
    writeToScreen("执行关闭事件，开始重连");
    reconnect();
  }
}

function initWsEventHandle () {
  try {
    wsObj.onopen = function (ev) {
      onWsOpen(ev);
    }
    wsObj.onmessage = function (ev) {
      onWsMessage(ev)
    }
    wsObj.onclose = function (ev) {
      writeToScreen("执行关闭事件，开始重连");
      onWsClose(ev);
      reconnect()
    }
    wsObj.onerror = function (ev) {
      writeToScreen("执行error事件，开始重连");
      onWsClose(ev);
      reconnect()
    }
  } catch (e) {
    writeToScreen("绑定事件没有成功");
    reconnect()
  }


}

function onWsClose () {

}


//重连
function reconnect () {
  if (lockReconnect) return;
  console.log("1秒后重连");
  lockReconnect = true;
  wsCreateHandler && clearTimeout(wsCreateHandler);
  wsCreateHandler = setTimeout(function () {
    console.log("重连开始");
    createWebSocket();
    lockReconnect = false;
    console.log("重连完成");
  }, 1000)
}